package com.atguigu.gmall.activity.controller;

import com.atguigu.gmall.activity.service.SeckillGoodsService;
import com.atguigu.gmall.activity.util.CacheHelper;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.common.util.MD5;
import com.atguigu.gmall.model.activity.OrderRecode;
import com.atguigu.gmall.model.activity.SeckillGoods;
import com.atguigu.gmall.model.activity.UserRecode;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.order.client.OrderFeignClient;
import com.atguigu.gmall.user.client.UserFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


/**
 * @author atguigu-mqx
 */
@RestController
@RequestMapping("/api/activity/seckill")
public class SeckillGoodsApiController {

    @Autowired
    private SeckillGoodsService seckillGoodsService;

    @Autowired
    private RabbitService rabbitService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private OrderFeignClient orderFeignClient;



    //  定义查询所有
    @GetMapping("/findAll")
    public List<SeckillGoods> findAll(){
        return seckillGoodsService.findAll();
    }

    //  根据skuId 来获取详情！
    @GetMapping("/getSeckillGoods/{skuId}")
    public SeckillGoods getSeckillGoods(@PathVariable Long skuId){
        return seckillGoodsService.findSeckillGoodsBySkuId(skuId);
    }

    //  http://api.gmall.com/api/activity/seckill/auth/getSeckillSkuIdStr/24
    @GetMapping("auth/getSeckillSkuIdStr/{skuId}")
    public Result getSeckillSkuIdStr(@PathVariable Long skuId, HttpServletRequest request){
        //  获取用户Id
        String userId = AuthContextHolder.getUserId(request);
        //  判断 必须在秒杀开始之后，结束之前生成！
        SeckillGoods seckillGoods = this.seckillGoodsService.findSeckillGoodsBySkuId(skuId);
        if (seckillGoods!=null){
            //  判断  当前系统时间 与开始时间 与 结束时间
            Date currentTime = new Date();
            if (DateUtil.dateCompare(seckillGoods.getStartTime(),currentTime) &&
            DateUtil.dateCompare(currentTime,seckillGoods.getEndTime())){
                //  对用户Id 进行加密
                //  String skuIdStr = DigestUtils.md5DigestAsHex(userId.getBytes());
                String skuIdStr = MD5.encrypt(userId);
                //  获取到下单码
                return Result.ok(skuIdStr);
            }
        }
        return Result.fail().message("获取下单码失败!");
    }

    //  下单控制器！  /api/activity/seckill/auth/seckillOrder/{skuId}?skuIdStr=x;
    @PostMapping("auth/seckillOrder/{skuId}")
    public Result seckillOrder(@PathVariable Long skuId,HttpServletRequest request){
        //  如果下单成功，则需要将 isCheckOrder = true;
        //  校验下单码：  userId 进行md5加密！
        String userId = AuthContextHolder.getUserId(request);
        //  获取前端传递的下单码！
        String skuIdStr = request.getParameter("skuIdStr");
        //  如果校验码不相等;返回提示
        if (!skuIdStr.equals(MD5.encrypt(userId))){
            return Result.build(null, ResultCodeEnum.SECKILL_ILLEGAL);
        }
        //  状态位一开始时，初始化的： skuId:1
        String status = (String) CacheHelper.get(skuId.toString());
        //  判断
        if (StringUtils.isEmpty(status)){
            //  return Result.fail().message("下单失败.");
            return Result.build(null, ResultCodeEnum.SECKILL_ILLEGAL);
        }else if ("0".equals(status)){
            return Result.build(null, ResultCodeEnum.SECKILL_FINISH);
        }else {
            //  1 需要将秒杀的用户放入到队列中！
            UserRecode userRecode = new UserRecode();
            userRecode.setSkuId(skuId);
            userRecode.setUserId(userId);

            //  将这个对放入队列中！
            //  发送的消息内容；
            this.rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_SECKILL_USER,MqConst.ROUTING_SECKILL_USER,userRecode);
        }
        //  默认返回！
        return Result.ok();
    }

    // checkOrder 检查订单状态：/api/activity/seckill/auth/checkOrder/{skuId}
    @GetMapping("auth/checkOrder/{skuId}")
    public Result checkOrder(@PathVariable Long skuId,HttpServletRequest request){
        //  获取用户Id
        String userId = AuthContextHolder.getUserId(request);
        //  调用服务层方法！
        //  默认返回！
        return seckillGoodsService.checkOrder(skuId,userId);
    }

    //  秒杀订单！
    @GetMapping("/auth/trade")
    public Result authTrade(HttpServletRequest request){
        //  创建一个map 集合！  userAddressList  detailArrayList totalNum totalAmount
        HashMap<String, Object> map = new HashMap<>();
        //  获取到收货地址列表！
        String userId = AuthContextHolder.getUserId(request);
        //  远程调用！userFeignClient
        List<UserAddress> userAddressList = userFeignClient.findUserAddressListByUserId(userId);
        //  订单明细 ---> 用户秒杀的商品！
        //  hash key =  seckill:orders   field = userId  value = orderRecode
        OrderRecode orderRecode = (OrderRecode) this.redisTemplate.boundHashOps(RedisConst.SECKILL_ORDERS).get(userId);
        //  这个就是用户要秒杀的那个商品！
        SeckillGoods seckillGoods = orderRecode.getSeckillGoods();

        List<OrderDetail> detailArrayList = new ArrayList<>();
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setSkuId(seckillGoods.getSkuId());
        //  这个秒杀的商品数量 1
        orderDetail.setSkuNum(orderRecode.getNum());
        orderDetail.setSkuName(seckillGoods.getSkuName());
        orderDetail.setImgUrl(seckillGoods.getSkuDefaultImg());
        //  展示价格的时候，要给秒杀价格！
        orderDetail.setOrderPrice(seckillGoods.getCostPrice());

        //  添加到集合中！
        detailArrayList.add(orderDetail);

        //        OrderInfo orderInfo = new OrderInfo();
        //        orderInfo.setOrderDetailList(detailArrayList);
        //        orderInfo.sumTotalAmount();
        //  保存收货地址列表！
        map.put("userAddressList",userAddressList);
        //  保存订单明细！
        map.put("detailArrayList",detailArrayList);
        //  秒杀的时候我们就发布一件商品！限制每个人只能购买一件！
        map.put("totalNum",orderRecode.getNum());
        //  秒杀的时候我们就发布一件商品！限制每个人只能购买一件！ 这个价格就是秒杀价格！
        map.put("totalAmount",seckillGoods.getCostPrice());
        //  如果允许发布多件商品的时候！
        //  map.put("totalAmount",orderInfo.getTotalAmount());
        //  返回map
        return Result.ok(map);
    }

    //  提交订单！/api/activity/seckill/auth/submitOrder
    //  需要将页面提交的json 数据转变为java 对象！
    @PostMapping("auth/submitOrder")
    public Result submitOrder(@RequestBody OrderInfo orderInfo,HttpServletRequest request){
        //  获取用户Id
        String userId = AuthContextHolder.getUserId(request);
        //  将用户Id 赋值订单对象
        orderInfo.setUserId(Long.parseLong(userId));
        //  保存到对应数据库中！ orderInfo, orderDetial;
        //  远程调用保存订单控制器！
        Long orderId = orderFeignClient.submitOrder(orderInfo);
        if (orderId==null){
            return Result.fail().message("提交订单失败!");
        }
        //  删除一个预下单信息！ hdel key field
        this.redisTemplate.boundHashOps(RedisConst.SECKILL_ORDERS).delete(userId);
        //  保存一个真正的订单！
        //  hash key = "seckill:orders:users" field = userId value = orderId
        this.redisTemplate.boundHashOps(RedisConst.SECKILL_ORDERS_USERS).put(userId,orderId.toString());
        //  默认返回
        return Result.ok(orderId);
    }



}
